const ejs = require('ejs')
const fs = require('fs')
const path = require('path')

function update() {
  const dirName = path.join(__dirname, '../src/contents')

  const dirs = fs.readdirSync(dirName)

  const dir = []
  dirs.forEach(item => {
    dir.push(path.join(dirName,item))
  })


  let arr = []
  dir.forEach((item, index) => {
    arr.push(fs.readdirSync(item).map(item => {
      return item.substring(0 ,item.lastIndexOf('.'))
    }))
  })
  
  let template = fs.readFileSync(path.join(__dirname,'./template.ejs'),{encoding: 'utf-8'})

  let result = ejs.render(template, {
    mainLayout: arr[1],
    mainPath: 'MainLayout',
    functions: arr[0],
    funcPath: 'Functions',
    lastCapitalizationWord,
    toFirstWordLower
  })
  fs.writeFileSync(path.join(__dirname,"../src/router/index.js"),result,{encoding:"utf-8"})

}

fs.watch(path.join(__dirname,"../src/contents/Functions"),{encoding:"utf-8"},(event) => {
  update()
})

fs.watch(path.join(__dirname,"../src/contents/MainLayout"),{encoding:"utf-8"},(event) => {
  update()
})

function lastCapitalizationWord(str){
  let arr = str.split('')
  for(let i = arr.length -1; i > 0; i--) {
    if(/[A-Z]/.test(arr[i])){
      return i
    }
  }
}

function toFirstWordLower(str){
  return str[0].toLocaleLowerCase() + str.substring(1)
}